const db = require('../db.config')
const Sequelize = db.sequelize
const jwt = require('../utils/jwt')

const Token = Sequelize.import('../schema/token.js')
Token.sync({force: false})

class TokenModule {
  /**
   * 新建token
   * @param data {name: String, password: String }
   */
  static async createToken(data) {
    return await Token.create({
      token: jwt.createToken(data),
      name: data.name,
      password: data.password,
      roles: data.roles,
      createAt: new Date
    })
  }

  /**
   * 销毁token
   * @param name/Token
   */
  static async destroyTokenByName(name) {
    Token.destroy({
      'where': {
        name: name
      }
    })
  }
  static async destroyTokenByToken(token) {
    Token.destroy({
      'where': {
        token: token
      }
    })
  }

  /**
   * 查询Token
   * @param name : String
   */

  static async getTokenByName(name) {
    let value = await Token.findAll({
      where: {
        name: name
      }
    })

    return value
  }

  /**
   * 列出所有token
   * 
   */
  static async getAllToken() {
    return await Token.findAll()
  }
}

module.exports = TokenModule